package com.chenjiajin.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.CellData;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.alibaba.excel.util.DateUtils;
import org.apache.poi.ss.usermodel.DateUtil;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 自定义日期转换器
 * 导入的时候: 将 时间(Date) 转为 时间戳(Long)
 * 导出的时候: 将 时间戳(Long) 转为 时间(Date)
 *
 * @author ChenJiaJin
 */
public class DateConverter implements Converter<Long> {

    @Override
    public Class<?> supportJavaTypeKey() {
        return Long.class;
    }

    @Override
    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.NUMBER;
    }

    @Override
    public Long convertToJavaData(CellData cellData, ExcelContentProperty excelContentProperty, GlobalConfiguration globalConfiguration) throws ParseException {
        Date date;
        if (excelContentProperty == null || excelContentProperty.getDateTimeFormatProperty() == null) {
            String stringValue = cellData.getStringValue();   // 2022/04/12 19:18:51
            date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(stringValue);
        } else {
            date = DateUtil.getJavaDate(cellData.getNumberValue().doubleValue(), excelContentProperty.getDateTimeFormatProperty().getUse1904windowing(), null);
        }
        return date.getTime();
    }

    @Override
    public CellData convertToExcelData(Long value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) {
        Date date = new Date(value);
        if (contentProperty == null || contentProperty.getDateTimeFormatProperty() == null) {
            return new CellData(DateUtils.format(date, "yyyy-MM-dd HH:mm:ss"));
        } else {
            return new CellData(DateUtils.format(date, contentProperty.getDateTimeFormatProperty().getFormat()));
            //return new CellData(DateUtils.format(date, "yyyy-MM-dd HH:mm:ss"));  // 2022-04-08 00:00:00
        }


    }


}
